<template>
  <el-dialog v-model="model" width="500">
    <template #header>
      <div class="my-header" v-if="!props.rows.set">
        分享笔记：{{ props.rows.title }}
      </div>
      <div class="my-header" v-else>
        <div>数据</div>
        <div style="display: flex; justify-content: space-between; color: #999">
          <span>阅读人数:{{ props.rows.set.reading_times }}</span>
          <span
            >分享有效期:
            {{ new Date(props.rows.set.effective_time).toLocaleString() }}</span
          >
        </div>
      </div>
    </template>
    <el-form
      :model="form"
      label-width="auto"
      ref="formRef"
      label-position="left"
      style="max-width: 600px"
    >
      <el-form-item label="权限:">
        <el-radio-group
          :disabled="disabledButton && !isEdit"
          v-model="form.permission"
          @change="handleChangeRole"
        >
          <el-radio :value="1">允许编辑</el-radio>
          <el-radio :value="0">仅查看</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效期:">
        <el-radio-group
          :disabled="disabledButton && !isEdit"
          v-model="form.validDate"
          @change="handleChangeValid"
        >
          <el-radio :value="0">永久有效</el-radio>
          <el-radio :value="1">一年</el-radio>
          <el-radio :value="2">30天</el-radio>
          <el-radio :value="3">一周</el-radio>
          <el-radio :value="4">一天</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="分享链接:">
        <el-input readonly v-model="form.link" />
      </el-form-item>
      <el-form-item
        label="分享密码:"
        prop="password"
        :rules="[{ validator: validatePass, trigger: ['blur', 'change'] }]"
      >
        <div
          style="
            width: 100%;
            display: flex;
            justify-content: space-between;
            gap: 10px;
          "
        >
          <div
            style="
              display: flex;
              justify-content: space-between;
              gap: 10px;
              align-items: center;
            "
          >
            <el-input
              :disabled="disabledButton && !isEdit"
              v-model="form.password"
              style="width: 100px"
              maxlength="6"
              minlength="6"
              @input="handleUpdateSharePwd"
            />
            <el-icon
              v-if="!disabledButton || isEdit"
              @click="handleRefreshPwd"
              style="cursor: pointer"
            >
              <Refresh />
            </el-icon>
          </div>
          <div>
            <el-button
              v-if="!disabledButton && !isEdit"
              :loading="createLinkLoading"
              @click="createShareLink(formRef)"
              type="primary"
            >
              创建分享链接
            </el-button>
            <template v-else>
              <el-button @click="stopShareNoteLink">停止分享</el-button>
              <el-button type="primary" @click="submitForm(formRef)">
                复制链接
              </el-button>
            </template>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { ref, watch, computed, reactive, onMounted, inject } from 'vue'
import { debounce } from '@/utils/tools.ts'
import { copyString } from '@/utils/index'
import {
  httpCreateShareLink,
  httpStopShareLink,
  httpUpdateShareAuthority,
} from '@/api/note'
import { ElMessage, ElMessageBox } from 'element-plus'
const base = import.meta.env.VITE_BASE_PATH
const props = defineProps({
  rows: {
    type: Object,
    default: () => {},
  },
})
const isEdit = ref(false)
const disabledButton = ref(false) // 是否已经创建分享链接了
const model = defineModel()
const form = reactive({
  permission: 0,
  validDate: 3,
  link: '',
  password: randomDigits(),
})
watch(
  () => model.value,
  (val) => {
    if (val) {
      disabledButton.value = props.rows.set // true就已经创建了 false 就是第一次创建
      isEdit.value = props.rows.set
      if (isEdit.value) {
        form.link =
          window.location.origin +
          `${base}/share-middle?id=${props.rows.id}&uid=${props.rows.set.uuid}`
        form.password = props.rows.set.share_password
      }
    }
  },
  // {
  //   immediate:true,
  //   deep:true
  // }
)

const updateBreadcrumb = inject('updateBreadcrumb')

function randomDigits() {
  let randomNum = ''
  for (let i = 0; i < 6; i++) {
    randomNum += Math.floor(Math.random() * 10)
  }
  return randomNum
}
const formRef = ref()
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入分享密码'))
  } else if (!/^\d{6}$/.test(value)) {
    // 密码只能为6位数字
    callback(new Error('密码长度为6位数字'))
  } else {
    callback()
  }
}
const createLinkLoading = ref(false)
// 创建分享链接
const createShareLink = (formEl) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      createLinkLoading.value = true
      const res = await httpCreateShareLink({
        fd_id: props.rows.id,
        authority: form.permission,
        effective_time_type: form.validDate,
        share_password: form.password,
      })
      if (res) {
        updateBreadcrumb()
        disabledButton.value = true
        form.link =
          window.location.origin +
          `${base}/share-middle?id=${props.rows.id}&uid=${res.uuid}`
      }
      createLinkLoading.value = false
    }
  })
}
const stopShareNoteLink = () => {
  ElMessageBox.confirm('确认取消分享?', '取消分享', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await httpStopShareLink({
        fd_id: props.rows.id,
      })
      if (res) {
        updateBreadcrumb()
        model.value = false
        ElMessage({
          type: 'success',
          message: '取消分享成功',
        })
      }
    })
    .catch(() => {
      // ElMessage({
      //   type: 'info',
      //   message: '取消分享失败',
      // })
    })
}
const handleRefreshPwd = () => {
  form.password = randomDigits()
  // TODO: 调用接口
  formRef.value.clearValidate('password')
  if (!disabledButton.value) return
  handleUpdateShare()
  //   updateBreadcrumb()
}
const handleUpdateShare = debounce(async () => {
  await formRef.value.validateField('password', async (valid) => {
    if (valid) {
      const res = await httpUpdateShareAuthority({
        share_id: props.rows.id,
        authority: form.permission,
        effective_time_type: form.validDate,
        share_password: form.password,
      })
      if (res) {
        updateBreadcrumb()
        ElMessage({
          type: 'success',
          message: '更新成功',
        })
      }
    }
  })
}, 1000)
const handleUpdateSharePwd = async (item) => {
  if (!disabledButton.value) return
  handleUpdateShare()
}
const handleChangeRole = async (item) => {
  //   updateBreadcrumb()
  if (!disabledButton.value) return
  handleUpdateShare()
}
/**
 * @description: 时间
 */
const handleChangeValid = async (item) => {
  if (!disabledButton.value) return
  handleUpdateShare()
}

const submitForm = (formEl) => {
  copyString("笔记链接：" + form.link + "\n分享密码：" + form.password)
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style scoped lang="scss"></style>
